/* Benchmark pour mesurer et tester la vitesse de transmission des messages  */

#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
#define BUFFER_SIZE 65536

int main (int argc, char **argv)
{
	FILE *file = NULL;

	int int_buff[BUFFER_SIZE];
	char char_buff[BUFFER_SIZE];
	int n, myid;
	int buflen = 0, ntimes = 500, index = 1, buffIncreas = 500;
	double starttime, endtime;
	MPI_Status status;

	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &myid);

	/* Processus Emetteur */

	if (myid == 0)
	{
		file = fopen("results.csv", "w");

		for (;;)
		{
			buflen = buffIncreas * index;

			int_buff[0] = ntimes;
			MPI_Send(int_buff, 1, MPI_INT, 1, 2, MPI_COMM_WORLD);

			if(index > 130){ break; }

			for (n = 0; n < buflen; n++) char_buff[n] = '0';

			int_buff[0] = buflen;
			MPI_Send(int_buff, 1, MPI_INT, 1, 2, MPI_COMM_WORLD);

			starttime = MPI_Wtime();

			for (n = 0; n < ntimes; n++)
			{
				MPI_Send(char_buff, buflen, MPI_CHAR, 1, 1, MPI_COMM_WORLD);
				MPI_Recv(char_buff, buflen, MPI_CHAR, 1, 1, MPI_COMM_WORLD, &status);
			}

			endtime = MPI_Wtime();

			printf("Total : %f secondes\nPar cycle : %f\n", endtime-starttime, (endtime-starttime)/(double)ntimes);
            fflush(stdout);

            fprintf(file, "%u %c %f \n", buflen, ',', (endtime-starttime)/(double)ntimes);

            index++;
		}

		fclose(file);
	}
	

	/* Processus Recepteur*/

	if (myid == 1)
	{
		for (;;)
		{
			MPI_Recv(int_buff, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
			ntimes = int_buff[0];

			if(index > 130){ break; }

			MPI_Recv(int_buff, 1, MPI_INT, 0, 2, MPI_COMM_WORLD, &status);
			buflen = int_buff[0];

			for (n = 0; n< ntimes; n++)
			{
				MPI_Recv(char_buff, buflen, MPI_CHAR, 0, 1, MPI_COMM_WORLD, &status);
				MPI_Send(char_buff, buflen, MPI_CHAR, 0, 1, MPI_COMM_WORLD);
			}

			index++;
		}
	}

	MPI_Finalize();

	return EXIT_SUCCESS;
}
